package lesson15;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class MyDelayTask implements Delayed {

    private String name;

    private long start = System.currentTimeMillis();

    private long time;

    public MyDelayTask(String name, long time){
        this.name = name;
        this.time = time;
    }


    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert((start + time) - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public String toString() {
        return "MyDelayQueue{" + "name='" + name + '\'' + ", time=" + time + '}';
    }

    public static void main(String[] args) throws InterruptedException {

        DelayQueue<MyDelayTask> delayQueue  = new DelayQueue();

        new Thread(() ->{
            delayQueue.offer(new MyDelayTask("task1",10000));
            delayQueue.offer(new MyDelayTask("task2",3900));
            delayQueue.offer(new MyDelayTask("task3",1900));
            delayQueue.offer(new MyDelayTask("task4",5900));
            delayQueue.offer(new MyDelayTask("task5",6900));
            delayQueue.offer(new MyDelayTask("task6",7900));
            delayQueue.offer(new MyDelayTask("task7",4900));
        }).start();

        while (true){
            System.out.println(delayQueue.take().toString());
        }
    }
}
